package com.mall.gateway.config;

import org.slf4j.MDC;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import java.util.UUID;

/**
 * WebFlux日志追踪过滤器
 * 仅在响应式Web应用中生效
 */
@Component
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
public class GatewayLogTraceWebFilter implements WebFilter {

    private static final String TRACE_ID = "traceId";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        // 添加链路追踪ID
        String traceId = UUID.randomUUID().toString().replace("-", "");
        MDC.put(TRACE_ID, traceId);

        try {
            // 设置响应头
            exchange.getResponse().getHeaders().add(TRACE_ID, traceId);
            
            // 继续处理请求
            return chain.filter(exchange)
                    .doFinally(signalType -> {
                        // 清除MDC中的数据
                        MDC.clear();
                    });
        } catch (Exception e) {
            // 确保在异常情况下也能清除MDC
            MDC.clear();
            throw e;
        }
    }
}